<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>号源信息</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <script src="/js/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h2 class="text-center mb-4">号源信息</h2>
    <!-- 日期选择下拉框 -->
    <div class="mb-3">
        <label for="dateSelector" class="form-label">选择日期</label>
        <select id="dateSelector" class="form-select"></select>
    </div>

    <!-- 动态加载区域 -->
    <ul id="scheduleList" class="list-group"></ul>
</div>

<script>
    let globalScheduleData = []; // 全局号源数据

    $(document).ready(function () {
        const urlParams = new URLSearchParams(window.location.search);
        const doctorId = urlParams.get('doctorId');

        if (!doctorId) {
            alert("医生ID不能为空");
            return;
        }

        // 获取号源信息
        $.get('/users/getScheduleByDoctorId/' + doctorId, function (data) {
            globalScheduleData = data; // 存储到全局变量
            console.log('【号源数据】共加载', data.length, '条记录');
            data.forEach((schedule, index) => {
                console.log(`第 ${index + 1} 条号源:`, schedule);
            });

            // 或者使用表格形式更清晰地展示（推荐）
            console.table(data);
            // 清空列表
            $('#scheduleList').empty();

            // 提取唯一日期
            const dates = [...new Set(data.map(schedule => schedule.date))];

            // 填充日期下拉框
            const dateSelector = $('#dateSelector');
            dateSelector.empty().append('<option value="">请选择日期</option>');
            dates.forEach(date => {
                dateSelector.append(`<option value="${date}">${date}</option>`);
            });

            // 默认渲染全部号源
            renderSchedules(data);

            // 监听日期选择事件
            dateSelector.on('change', function () {
                const selectedDate = $(this).val();
                const filtered = selectedDate
                    ? data.filter(schedule => schedule.date === selectedDate)
                    : data;
                renderSchedules(filtered);
            });
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.error('获取号源数据失败:', textStatus, errorThrown);
            alert('获取号源数据失败');
        });

        // 渲染号源列表
        function renderSchedules(schedules) {
            $('#scheduleList').empty();

            if (schedules?.length > 0) {
                $.each(schedules, function (index, schedule) {
                    const isAvailable = schedule.availableNumber > 0;
                    const buttonClass = isAvailable ? 'btn btn-primary' : 'btn btn-secondary disabled';

                    $('#scheduleList').append(
                        `<li class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <strong>日期:</strong> ${schedule.date}<br>
                                <strong>时间段:</strong> ${schedule.period === 1 ? '上午' : '下午'}<br>
                                <strong>剩余号数:</strong> ${schedule.availableNumber}<br>
                                <strong>价格:</strong> ${schedule.price}
                            </div>
                            <button class="${buttonClass}" ${isAvailable ? `data-schedule-id="${schedule.id}"` : ''}>${isAvailable ? '预约' : '已约满'}</button>
                        </li>`
                    );
                });

                // 绑定预约事件
                // 修改预约事件绑定逻辑
                $('#scheduleList')
                    .off('click', 'button.btn-primary')
                    .on('click', 'button.btn-primary', function () {
                        const $btn = $(this);
                        if ($btn.hasClass('disabled')) return;

                        $btn.addClass('disabled').text('处理中...');

                        const scheduleId = parseInt($btn.data('schedule-id'));
                        if (!scheduleId) {
                            alert("无效的号源ID");
                            $btn.removeClass('disabled').text('预约');
                            return;
                        }

                        // ✅ 正确获取 schedule 对象
                        const schedule = globalScheduleData.find(s => s.id === scheduleId);
                        if (!schedule) {
                            console.error("未找到 schedule", scheduleId);
                            alert("未找到对应的号源信息");
                            $btn.removeClass('disabled').text('预约');
                            return;
                        }

                        // 发送预约请求
                        $.ajax({
                            url: '/users/addAppointment',
                            method: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(schedule), // ✅ 使用查找到的 schedule 对象
                            success: function (response) {
                                if (response.success) {
                                    alert('预约成功');
                                    $btn.removeClass('btn-primary').addClass('btn-secondary disabled').text('已预约');

                                    // 更新剩余号数
                                    const $li = $btn.closest('li');
                                    let availableNumber = parseInt($li.find('strong:contains("剩余号数")').next().text());

                                    if (availableNumber > 0) {
                                        availableNumber--;
                                        $li.find('strong:contains("剩余号数")').next().text(availableNumber);

                                        if (availableNumber === 0) {
                                            $btn.removeClass('btn-primary').addClass('btn-secondary disabled').text('已约满');
                                        }
                                    }
                                } else {
                                    alert('预约失败: ' + response.message);
                                    $btn.removeClass('disabled').text('预约');
                                }
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.error('预约失败:', textStatus, errorThrown);
                                alert('预约失败');
                                $btn.removeClass('disabled').text('预约');
                            },
                            complete: function () {
                                $btn.removeClass('disabled').text('预约'); // 请求结束后恢复按钮状态
                            }
                        });
                    });


            } else {
                $('#scheduleList').append('<li class="list-group-item text-muted">暂无号源信息</li>');
            }
        }
    });
</script>

</body>
</html>
